package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.system.dao.MiddlegroundMenuRepository;
import com.ssy.lingxi.system.dao.MiddlegroundMenuRoleRepository;
import com.ssy.lingxi.system.dao.MiddlegroundRoleRepository;
import com.ssy.lingxi.system.dao.MiddlegroundRoleUserRepository;
import com.ssy.lingxi.system.dto.request.*;
import com.ssy.lingxi.system.dto.response.*;
import com.ssy.lingxi.system.entity.MiddlegroundMenuRole;
import com.ssy.lingxi.system.entity.MiddlegroundRole;
import com.ssy.lingxi.system.entity.MiddlegroundRoleUser;
import com.ssy.lingxi.system.model.constant.RoleConstant;
import com.ssy.lingxi.system.service.MiddlegroundRoleService;
import com.ssy.lingxi.system.utils.UserDetailsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class MiddlegroundRoleServiceImpl implements MiddlegroundRoleService {

    @Autowired
    MiddlegroundRoleRepository middlegroundRoleRepository;
    @Autowired
    UserDetailsUtil userDetailsUtil;

    @Autowired
    MiddlegroundMenuRoleRepository middlegroundMenuRoleRepository;

    @Resource
    MiddlegroundRoleUserRepository middlegroundRoleUserRepository;

    @Resource
    MiddlegroundMenuRepository middlegroundMenuRepository;

    @Resource
    JdbcTemplate jdbcTemplate;

    /**
     * 查询角色列表
     *
     * @param request
     * @param middlegroundRoleRequest
     * @author wrc
     * @date 2020/5/22
     */
    @Override
    public Wrapper<PageData<MiddlegroundRoleResponse>> roleList(HttpServletRequest request, MiddlegroundRoleRequest middlegroundRoleRequest) {
        PageData pageData = new PageData(0L, new ArrayList());
        MiddlegroundRole middlegroundRole=new MiddlegroundRole();
        Example<MiddlegroundRole> example =Example.of(middlegroundRole);
        if (null != middlegroundRoleRequest.getName() && !"".equals(middlegroundRoleRequest.getName())) {
            middlegroundRole.setName(middlegroundRoleRequest.getName());
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
            example = Example.of(middlegroundRole,matcher);
        }
        if(null != middlegroundRoleRequest.getState()){
            middlegroundRole.setState( middlegroundRoleRequest.getState());
            example = Example.of(middlegroundRole);
        }
        Page<MiddlegroundRole>   all = middlegroundRoleRepository.findAll(example,PageRequest.of(middlegroundRoleRequest.getCurrent(), middlegroundRoleRequest.getPageSize(), Sort.by("id").ascending()));
        if (null != all && all.getTotalElements() > 0) {
            pageData = new PageData(all.getTotalElements(), all.toList());
        }
        return Wrapper.success(pageData);
    }

    /**
     * 添加角色
     * @param request
     * @param middlegroundRoleRequest
     * @author wrc
     * @date 2020/5/22
     */
    @Transactional
    @Override
    public Wrapper roleAdd(HttpServletRequest request,MiddlegroundRoleAddRequest middlegroundRoleRequest) {
        MiddlegroundUserLoginResponse loginUserDetails = userDetailsUtil.getLoginUserDetails(request);
        MiddlegroundRole middlegroundRole=new MiddlegroundRole();
        middlegroundRole.setState(RoleConstant.RoleState.ROLE_STATE_START);
        middlegroundRole.setName(middlegroundRoleRequest.getName());
        middlegroundRole.setCreateRole(loginUserDetails.getId());
        middlegroundRole.setCreateTime(System.currentTimeMillis());
        middlegroundRole.setDescribed(middlegroundRoleRequest.getDescribed());
        MiddlegroundRole save = middlegroundRoleRepository.save(middlegroundRole);
        List<MiddlegroundMenuRole> middlegroundMenuRoles=new ArrayList<>();
        List<Long> menuIds = middlegroundRoleRequest.getMenuIds();
        Long id = save.getId();
        menuIds.forEach(menuid->{
            MiddlegroundMenuRole middlegroundMenuRole=new MiddlegroundMenuRole();
            middlegroundMenuRole.setRoleId(id);
            middlegroundMenuRole.setMenuId(menuid);
            middlegroundMenuRoles.add(middlegroundMenuRole);
        });
        middlegroundMenuRoleRepository.saveAll(middlegroundMenuRoles);
        return Wrapper.success();
    }

    /**
     * 修改角色
     * @param middlegroundRoleRequest
     * @author wrc
     * @date 2020/5/22
     */
    @Transactional
    @Override
    public Wrapper roleUpdate(MiddlegroundRoleUpdateRequest middlegroundRoleRequest) {
        if(middlegroundRoleRequest.getId().equals(1L)){
            return Wrapper.fail("超级管理员不可以删除修改");
        }
        Optional<MiddlegroundRole> byId = middlegroundRoleRepository.findById(middlegroundRoleRequest.getId());
        if(!byId.isPresent()){
            return Wrapper.fail("角色不存在");
        }
        MiddlegroundRole middlegroundRole = byId.get();
        middlegroundRole.setDescribed(middlegroundRoleRequest.getDescribed());
        middlegroundRole.setUpdateTime(System.currentTimeMillis());
       // middlegroundRole.setState(middlegroundRoleRequest.getState());
        middlegroundRole.setName(middlegroundRoleRequest.getName());
        middlegroundRoleRepository.save(middlegroundRole);
        //先删除再添加
        middlegroundMenuRoleRepository.deleteAllByRoleIdEquals(middlegroundRoleRequest.getId());
        List<MiddlegroundMenuRole> middlegroundMenuRoles=new ArrayList<>();
        middlegroundRoleRequest.getMenuIds().forEach(menuid->{
            MiddlegroundMenuRole menuRole=new MiddlegroundMenuRole();
            menuRole.setRoleId(middlegroundRoleRequest.getId());
            menuRole.setMenuId(menuid);
            middlegroundMenuRoles.add(menuRole);
        });
        middlegroundMenuRoleRepository.saveAll(middlegroundMenuRoles);
        return Wrapper.success();
    }

    /**
     * 删除角色
     * @param middlegroundRoleRequest
     * @author wrc
     * @date 2020/5/22
     */
    @Transactional
    @Override
    public Wrapper roleDelete(MiddlegroundRoleDeleteRequest middlegroundRoleRequest) {
        //删除菜单
        MiddlegroundMenuRole middlegroundMenuRole =new MiddlegroundMenuRole();
        middlegroundMenuRole.setRoleId(middlegroundRoleRequest.getId());
        middlegroundMenuRoleRepository.delete(middlegroundMenuRole);
        //删除角色
        middlegroundRoleRepository.deleteById(middlegroundRoleRequest.getId());
        return Wrapper.success();
    }

    /**
     * 停用启用角色
     * @param request
     * @author wrc
     * @date 2020/7/29
     */
    @Override
    public Wrapper roleUpdateState(RoleUpdateStateRequest request) {
        Optional<MiddlegroundRole> byId = middlegroundRoleRepository.findById(request.getId());
        if(request.getId().equals(1L)){
            return Wrapper.fail("超级管理员不可以停用&启用");
        }
        if(!byId.isPresent()){
            return Wrapper.fail("角色不存在");
        }
        MiddlegroundRole middlegroundRole = byId.get();
        //停用的前提条件要求在此角色下的所有用户都已解除绑定关系，无效状态下，可修改及删除角色
        if(CommonConstant.State.STATE_STOP==request.getState()){
            List<MiddlegroundRoleUser> allByRoleIdEquals = middlegroundRoleUserRepository.findAllByRoleIdEquals(request.getId());
            if(null!=allByRoleIdEquals &&allByRoleIdEquals.size()>0){
                return Wrapper.fail("角色已经和用户绑定不能停用");
            }
        }
        middlegroundRole.setState(request.getState());
        middlegroundRole.setUpdateTime(System.currentTimeMillis());
        middlegroundRoleRepository.save(middlegroundRole);
        return Wrapper.success();
    }

    /**
     * 角色详情查询
     * @param request
     * @author wrc
     * @date 2020/7/29
     */
    @Override
    public Wrapper<MiddlegroundRoleDeatilsResponse> roleDetails(MiddlegroundRoleDeleteRequest request) {
        Optional<MiddlegroundRole> byId = middlegroundRoleRepository.findById(request.getId());
        if(!byId.isPresent()){
            return Wrapper.fail("角色不存在");
        }
        MiddlegroundRoleDeatilsResponse middlegroundRoleDeatilsResponse=new MiddlegroundRoleDeatilsResponse();
        MiddlegroundRole middlegroundRole = byId.get();
        middlegroundRoleDeatilsResponse.setId(middlegroundRole.getId());
        middlegroundRoleDeatilsResponse.setDescribed(middlegroundRole.getDescribed());
        middlegroundRoleDeatilsResponse.setName(middlegroundRole.getName());
        middlegroundRoleDeatilsResponse.setState(middlegroundRole.getState());
        //根据角色ID查询菜单列表
        List<MiddlegroundMenuRole> allByRoleIdEquals = middlegroundMenuRoleRepository.findAllByRoleIdEquals(request.getId());
        List<Long> collect = allByRoleIdEquals.stream().map(v -> v.getMenuId()).collect(Collectors.toList());
        List<Long> list = middlegroundMenuRepository.findAllById(collect).stream().filter(v -> v.getType() == CommonConstant.FileType.OSS_UPLOAD).map(v->v.getId()).collect(Collectors.toList());
        middlegroundRoleDeatilsResponse.setIds(list);
        return Wrapper.success(middlegroundRoleDeatilsResponse);
    }

    /**
     * 查询按钮集合
     *
     * @param request
     * @author wrc
     * @date 2020/7/29
     */
    @Override
    public Wrapper<RoleButtonListResponse> roleButtonList(RoleButtonListRequest request) {
        //根据角色ID查询菜单列表
        StringBuilder sbList = new StringBuilder();
        sbList.append("select m.id from cf_middleground_menu m left join cf_middleground_role_menu r on r.menu_id =m.id  where m.type=2 and ");
        sbList.append("m.parent_id=");
        sbList.append(request.getMenuId());
        sbList.append(" and r.role_id=");
        sbList.append(request.getId());
        List<RoleButtonListIdResponse> countryAreaListResponse = jdbcTemplate.query(sbList.toString(), new BeanPropertyRowMapper(RoleButtonListIdResponse.class));
        RoleButtonListResponse roleButtonListResponse=new RoleButtonListResponse();
        roleButtonListResponse.setIds(countryAreaListResponse.stream().map(v->v.getId()).collect(Collectors.toList()));
        return Wrapper.success(roleButtonListResponse);
    }
}
